package com.polaris.live.ui.party.widget.seat.base

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.im.sfs.bean.live.LiveRoomInfo
import com.polaris.live.im.sfs.bean.live.SendLiveMessage
import com.polaris.live.im.sfs.bean.live.payload.PartyEmojiPayloadBean
import com.polaris.live.ui.party.PartyUserStateUtil
import com.polaris.live.ui.party.widget.seat.PartyStreamProxy
import com.polaris.live.ui.party.widget.seat.bean.SeatBean
import com.polaris.live.ui.party.widget.seat.listener.PartySeatListener
import com.polaris.live.ui.party.widget.seat.listener.StreamManageListener
import com.polaris.live.ui.party.widget.seat.party_seat.SeatItemView

/**
 * BaseSeatView
 *
 * @author Created by 天晴 on 2024/2/29 15:58
 * @since 1.0.0
 **/
abstract class BaseSeatView(context: Context, attrs: AttributeSet?) :
    FrameLayout(context, attrs) {

    private var meSeat: BaseSeatItemView? = null //自己的座位信息
    private var mLastOnSeatState: Boolean = false //上次是否在座
    private var mLastSiteMicStatus: Int? = null //在座位上得语言状态
    private var mIsOnPause = false //是否是onPause状态

    private var mIsInit: Boolean = false //是否初始化

    private val mViews = mutableListOf<BaseSeatItemView>()

    private var minimize = false  //是否最小化

    /**
     * 麦位流管理
     */
    private var mPartyStreamManage: PartyStreamProxy? = null

    private var mPartySeatListener: PartySeatListener? = null

    /**
     * 座位数量
     */
    abstract fun getSeatCount(): Int

    abstract fun createView(seatId: Int): BaseSeatItemView


    /**
     * 初始化
     */
    fun initView() {
        for (seatId in 0 until getSeatCount()) {
            createView(seatId).apply {
                initSeatId(seatId)
                mViews.add(this)
                setOnSingleClickListener {
                    if (mIsInit) {
                        mPartySeatListener?.clickItem(seatId, getData())
                    }
                }
            }
        }
    }

    /**
     * 更新音浪
     */
    private val mStreamManageListener = object : StreamManageListener {
        override fun onCapturedSoundLevelUpdate(soundLevel: Float) {
            meSeat?.SoundLevelUpdate(soundLevel)
            meSeat?.let {
                mPartySeatListener?.soundLevelUpdate(it.getSeatId(), soundLevel)
            }
        }

        override fun onRemoteSoundLevelUpdate(seatId: Int, soundLevel: Float) {
            mViews[seatId].SoundLevelUpdate(soundLevel)
        }

    }

    /**
     * 更新单个座位数据
     */
    fun setUpdateDateSeat(seatId: Int, mLiveInfo: LiveRoomInfo) {
        mViews[seatId].setData(mLiveInfo)
        inspectMaishangZego()
    }

    /**
     * 展示emoji
     */
    fun showUserEmoji(message: SendLiveMessage) {
        val payload = message.payload as PartyEmojiPayloadBean
        val view = mViews.getOrNull(payload.site) ?: return
        if (view.getData().userBasicVo?.userId == payload.userId) {
            view.showEmoji(message)
        }
    }

    /**
     * 修改派对房用户职位
     * userId  房主id
     */
    fun upDataUserPosition(data: List<Long>, userId: Long) {
        //转成set提高查找效率
        val userIds = data.toSet()
        for (user in mViews) {
            if (user.getData().userBasicVo?.userId == userId) {
                user.upDataUserPosition(SeatItemView.HOMEOWNER)
            } else {
                if (userIds.contains(user.getData().userBasicVo?.userId)) {
                    user.upDataUserPosition(SeatItemView.ADMINISTRATOR)
                } else {
                    user.upDataUserPosition(SeatItemView.GENERAL_AUDIENCE)
                }
            }
        }
    }

    /**
     * 设置加入时的麦位数据全部,初始化
     *
     * userId 主播id
     */
    fun setInitJoinData(mLiveInfo: LiveRoomInfo, userId: Long, lastPartyStreamProxy: PartyStreamProxy? = null) {
        mIsInit = true
        if (lastPartyStreamProxy != null) {
            mPartyStreamManage?.destroyStreams()
            mPartyStreamManage = lastPartyStreamProxy
        }
        if (mPartyStreamManage == null) {
            mPartyStreamManage = PartyStreamProxy()
        }
        //加入时添加监听
        mPartyStreamManage?.setJoinRoom(mStreamManageListener)
        mViews.forEach {
            it.setData(mLiveInfo, userId)
        }

        inspectMaishangZego()
    }

    /**
     * 根据userId查找座位上是否有这个人
     */
    fun getSeatBeanByUserId(userId: Long): SeatBean? {
        return mViews.firstOrNull { it.getData().userBasicVo?.userId == userId }?.getData()

    }

    /**
     * 获取一个无人的麦位
     */
    fun getNoHavaSeat(): SeatBean? {
        return mViews.firstOrNull { it.getData().userBasicVo == null }?.getData()
    }

    /**
     * 获取自己座位信息
     */
    fun getMeSeatBean(): SeatBean? {
        return meSeat?.getData()
    }

    /**
     * 检查麦上用户 推拉流
     */
    fun inspectMaishangZego() {
        if (mIsOnPause) {
            return
        }
        var inSeat = false //自己在座位吗
        mViews.forEachIndexed { _, seatItemView ->
            val seatBean = seatItemView.getData()
            handStream(seatItemView)
            if (seatBean.userBasicVo?.userId == UserManager.getUserId()) {
                inSeat = true
                val nowMicStatus = seatBean.siteMicStatus
                if (!mLastOnSeatState || mLastSiteMicStatus != nowMicStatus) {
                    mLastSiteMicStatus = nowMicStatus
                    mPartySeatListener?.updateOneSelfSeat(seatBean)
                }
                PartyUserStateUtil.siteMicStatus = nowMicStatus

                mLastOnSeatState = true
                meSeat = seatItemView
                PartyUserStateUtil.inTheMaiSeat = true
            }
        }
        if (!inSeat) { //自己没上麦
            if (mLastOnSeatState) {
                mLastOnSeatState = false
                mPartySeatListener?.updateOneSelfSeat(null)
            }
            mLastSiteMicStatus = null
            meSeat = null
            PartyUserStateUtil.inTheMaiSeat = false
            PartyUserStateUtil.siteMicStatus = null
            stopPlishStream()
        } else {
            meSeat?.getData()?.let {
                if (it.siteMicStatus == 1) { //开了声音
                    publishStream(it)
                } else {
                    stopPlishStream()
                }
            }
        }
    }

    /**
     * 判断是否需要拉流
     */
    private fun handStream(seatItemView: BaseSeatItemView) {
        val seatBean = seatItemView.getData()
        if (seatBean.userBasicVo == null || //没人不拉流
            seatBean.siteStreamId == null ||//没有流Id
            seatBean.siteLock == true || //被锁不拉流
            seatBean.siteMicStatus != 1   //关闭了麦克风
        ) {
            mPartyStreamManage?.closeStreamsBySeatId(seatItemView.getSeatId())
            return
        }
        if (seatBean.userBasicVo?.userId == UserManager.getUserId()) {//自己不拉流
            mPartyStreamManage?.closeStreamsBySeatId(seatItemView.getSeatId())
            return
        }
        seatBean.siteStreamId?.let {//没有流Id
            mPartyStreamManage?.openStream(seatItemView.getSeatId(), it)
        }
    }

    /**
     * 推流
     */
    private fun publishStream(seatBean: SeatBean) {
        if (seatBean.siteLock != true) {
            seatBean.siteStreamId?.let {
                mPartyStreamManage?.publishStream(it)
            }

        }
    }

    fun onResume() {
        mIsOnPause = false
    }

    fun onPause() {
        mIsOnPause = true
        if (!minimize) {
            stopPlishStream()
            mPartyStreamManage?.clearStreams()
        }
    }

    /**
     * 停止推流
     */
    fun stopPlishStream() {
        mPartyStreamManage?.stopPublishStream()
    }

    fun setPartySeatListener(listener: PartySeatListener) {
        mPartySeatListener = listener
    }

    /**
     * 获取所有座位的用户信息
     */
    fun getSeatData(): MutableList<SeatBean> {
        val list = mutableListOf<SeatBean>()
        mViews.forEach {
            list.add(it.getData())
        }
        return list
    }

    /**
     * 获取流控制器
     */
    fun getPartyStreamProxy(): PartyStreamProxy? {
        return mPartyStreamManage
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mIsInit = false
        destroyView()
    }

    /**
     * 重置
     */
    fun reset() {
        mIsInit = false
        meSeat = null
        if (!minimize) {
            mViews.forEach {
                it.resetView()
            }
            PartyUserStateUtil.inTheMaiSeat = false
            PartyUserStateUtil.siteMicStatus = null
            mPartyStreamManage?.destroyStreams()
        }
    }


    /**
     * 释放
     */
    fun destroyView() {
        mIsInit = false
        if (!minimize) {
            mPartyStreamManage?.destroyStreams()
        }
    }

    fun setMinimize(minimize: Boolean) {
        this.minimize = minimize
    }

}